package day29;

import javax.lang.model.element.VariableElement;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @project 黄鹤楼酒业质量管理系统(QMS)
 * @module 模块:
 * @desc: 描述:
 * @author: 王丹
 * @create: 2023-09-08 17:24
 **/
public class Test {

    static Semaphore semaphore = new Semaphore(5);

    public static void main(String[] args) {
        SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                boolean flag = false;
                try {
                    flag = semaphore.tryAcquire(100, TimeUnit.MICROSECONDS);
                    if (flag) {
                        //休眠2秒，模拟下单操作
                        System.out.println(sdFormat.format(new Date()) + "" + Thread.currentThread() + "，尝试下单中。。。。。");
                        TimeUnit.SECONDS.sleep(2);
                    } else {
                        System.out.println(sdFormat.format(new Date()) + "" + Thread.currentThread() + "，秒杀失败，请稍微重试！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (flag) {
                        semaphore.release();
                    }

                }
            }).start();

        }
    }
}
